package com.wzy.Controller.admin;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wzy.entity.Hero;
import com.wzy.service.HeroService;
import com.wzy.service.ProvinceService;
import com.wzy.util.Pager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author wzy
 * @since 2021-02-09
 */
@Controller
@RequestMapping("/admin")
public class HerosController {

    @Autowired
    private HeroService heroService;

    @Autowired
    private ProvinceService provinceService;

//  首页
    @RequestMapping("/hero")
    public ModelAndView index(@RequestParam(value = "page",defaultValue = "1") Integer page, Hero condition){
        Pager<Hero> pager=this.heroService.list(condition, page);
        return new ModelAndView("admin/hero/hero")
                .addObject("pager",pager)
                .addObject("condition",condition)
                .addObject("provinces",this.provinceService.list());
    }

//  跳转到新增页
    @RequestMapping("/hero/append")
    public String append(Model model){
        model.addAttribute("provinces",this.provinceService.list());
        return "admin/hero/append";
    }

//  新增
    @PostMapping("/hero/append")
    public String append(Hero hero, RedirectAttributes attributes){
        hero.setUserId((long) 1);
        if(this.heroService.append(hero)!=0){
            attributes.addFlashAttribute("message","新增成功");
        }else{
            attributes.addFlashAttribute("message","新增失败");
        }
        return "redirect:/admin/hero";
    }

    //  跳转到编辑页
    @RequestMapping("/hero/modify/{heroId}")
    public String modify(@PathVariable("heroId")Long heroId, Model model){
        model.addAttribute("hero",this.heroService.detail(heroId));
        model.addAttribute("provinces",this.provinceService.list());
        return "admin/hero/modify";
    }

    //  编辑
    @PostMapping("/hero/modify")
    public String modify(Hero hero, RedirectAttributes attributes){
        hero.setUpdateTime(new Date());
        if(this.heroService.updateById(hero)){
            attributes.addFlashAttribute("message","编辑成功");
        }else{
            attributes.addFlashAttribute("message","编辑失败");
        }
        return "redirect:/admin/hero";
    }

//  删除
    @RequestMapping("/hero/delete/{heroId}")
    public String delete(@PathVariable("heroId") Long heroId,RedirectAttributes attributes ){
        if(this.heroService.removeById(heroId)){
            attributes.addFlashAttribute("message","删除成功");
        }else{
            attributes.addFlashAttribute("message","删除失败");
        }
        return "redirect:/admin/hero";
    }

}

